package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.annotation.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
//import java.util.Date;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SysDeptController.class);

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 从GBase同步部门数据
     */
    @DataSource(value = DataSourceType.GBASE)
    @PreAuthorize("@ss.hasPermi('system:dept:sync')")
    @Log(title = "部门管理", businessType = BusinessType.SYNC)
    @GetMapping("/sync")
    public AjaxResult syncFromGbase() {
        try {
            List<SysDept> deptList = new ArrayList<>();
            String sql = "SELECT dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status, del_flag, create_by, create_time, update_by, update_time FROM jx.v_rydept ORDER BY parent_id NULLS FIRST";
            
            jdbcTemplate.query(sql, rs -> {
                SysDept dept = new SysDept();
                dept.setDeptId(rs.getLong("dept_id"));
                dept.setParentId(rs.getLong("parent_id"));
                dept.setAncestors(rs.getString("ancestors"));
                dept.setDeptName(rs.getString("dept_name"));
                dept.setOrderNum(rs.getInt("order_num"));
                dept.setLeader(rs.getString("leader"));
                dept.setPhone(rs.getString("phone"));
                dept.setEmail(rs.getString("email"));
                dept.setStatus(rs.getString("status"));
                dept.setDelFlag(rs.getString("del_flag"));
                dept.setCreateBy(rs.getString("create_by"));
                dept.setCreateTime(rs.getTimestamp("create_time"));
                dept.setUpdateBy(rs.getString("update_by"));
                dept.setUpdateTime(rs.getTimestamp("update_time"));
                deptList.add(dept);
            });

            // 先删除现有部门
            List<SysDept> existingDepts = deptService.selectDeptList(new SysDept());
            for (SysDept dept : existingDepts) {
                deptService.deleteDeptById_delete(dept.getDeptId());
            }

            // 按父部门ID排序
            deptList.sort((a, b) -> {
                if (a.getParentId().equals(0L)) return -1;
                if (b.getParentId().equals(0L)) return 1;
                return a.getParentId().compareTo(b.getParentId());
            });

            // 逐个插入
            for (SysDept dept : deptList) {
                //log.info("Inserting dept: {}", dept.toString());
                deptService.insertDept(dept);
            }

            return AjaxResult.success("同步成功，共同步 " + deptList.size() + " 条数据");
        } catch (Exception e) {
            log.error("同步部门数据失败", e);
            return AjaxResult.error("同步失败：" + e.getMessage());
        }
    }
}
